import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    error: null,
    users: [] // 存储所有注册的用户
  }),

  getters: {
    isLoggedIn: (state) => !!state.user
  },

  actions: {
    // 初始化加载用户数据
    init() {
      this.loadUsers()
      this.loadUser()
    },

    // 登录操作
    login(username, password) {
      // 这里是模拟登录验证逻辑
      // 首先检查是否有已注册的用户
      const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
      
      // 查找匹配的用户
      const matchedUser = users.find(user => 
        user.username === username && user.password === password
      )
      
      if (matchedUser) {
        this.user = {
          id: matchedUser.id,
          username: matchedUser.username,
          avatar: matchedUser.avatar,
          nickname: matchedUser.nickname
        }
        // 保存当前登录用户信息
        localStorage.setItem('user', JSON.stringify(this.user))
        this.error = null
        return true
      } else {
        this.error = '用户名或密码错误'
        return false
      }
    },

    // 注册操作
    register(username, password, nickname) {
      // 这里是模拟注册逻辑
      if (!username || !password || !nickname) {
        this.error = '请填写完整的注册信息'
        return false
      }
      
      // 获取已注册用户
      const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
      
      // 检查用户名是否已存在
      if (users.some(user => user.username === username)) {
        this.error = '用户名已被注册'
        return false
      }
      
      // 创建新用户
      const newUser = {
        id: Date.now(), // 模拟生成唯一ID
        username: username,
        password: password, // 在实际应用中应该加密存储
        avatar: 'https://picsum.photos/id/' + Math.floor(Math.random() * 1000) + '/200/200',
        nickname: nickname
      }
      
      // 保存新用户到本地存储
      users.push(newUser)
      localStorage.setItem('registeredUsers', JSON.stringify(users))
      
      // 自动登录
      this.user = {
        id: newUser.id,
        username: newUser.username,
        avatar: newUser.avatar,
        nickname: newUser.nickname
      }
      localStorage.setItem('user', JSON.stringify(this.user))
      
      this.error = null
      return true
    },

    // 登出操作
    logout() {
      this.user = null
      localStorage.removeItem('user')
    },

    // 从localStorage加载当前登录用户信息
    loadUser() {
      const user = localStorage.getItem('user')
      if (user) {
        this.user = JSON.parse(user)
      }
    },
    
    // 加载所有注册用户（仅用于验证）
    loadUsers() {
      const users = localStorage.getItem('registeredUsers')
      if (users) {
        this.users = JSON.parse(users)
      }
    }
  }
})